<?php

declare(strict_types=1);


namespace App\CustHub\Controller;

use Api\Service\v1\Work\EmployeeApiService;
use App\Chat\Constant\TalkEventConstant;
use App\Chat\Event\TalkEvent;
use App\Common\Redis\RedisCluster;
use App\Common\Robot\Robot;
use App\Common\Service\ExcelService;
use App\Common\Service\RemoteFileService;
use App\Common\Service\ShortChainService;
use App\CustHub\Constants\MsgTypeConstants;
use App\CustHub\Constants\OpSchemeTypeConstants;
use App\CustHub\Constants\RoomActiveRoomTypeConstants;
use App\CustHub\Constants\RoomTaskCenterTypeConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Dto\AddMsgTemplateDto;
use App\CustHub\Dto\OperationLogDto;
use App\CustHub\Dto\RoomTcContentDto;
use App\CustHub\Event\AutoKickTrigger;
use App\CustHub\Event\ChOperationLog;
use App\CustHub\Event\RoomActiveRoom;
use App\CustHub\Event\RoomOperationBehaviorAfter;
use App\CustHub\Event\SopNewUserTrigger;
use App\CustHub\Helpers\TagReplacer;
use App\CustHub\Interfaces\OpenWorkApplicationInterface;
use App\CustHub\Mapper\ChContactMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Mapper\ChRoomMapper;
use App\CustHub\Mapper\ChSyncTaskMapper;
use App\CustHub\Model\ChCorp;
use App\CustHub\Model\ChFriendCircleTask;
use App\CustHub\Model\ChRoom;
use App\CustHub\Model\ChRoomActiveRoom;
use App\CustHub\Model\ChRoomInviteActiveRoom;
use App\CustHub\Model\ChRoomMemberWarning;
use App\CustHub\Model\ChSyncTask;
use App\CustHub\Model\ChUser;
use App\CustHub\Model\MxShop;
use App\CustHub\Service\AppService;
use App\CustHub\Service\ChConfigService;
use App\CustHub\Service\ChCrowSendingService;
use App\CustHub\Service\ChFriendCircleTaskService;
use App\CustHub\Service\ChMaterialService;
use App\CustHub\Service\ChNewCustomerSchemeService;
use App\CustHub\Service\ChRoomActiveRoomService;
use App\CustHub\Service\ChRoomAutoTagConfigService;
use App\CustHub\Service\ChRoomInviteSchemeService;
use App\CustHub\Service\ChRoomKickUserService;
use App\CustHub\Service\ChRoomMemberWarningService;
use App\CustHub\Service\ChRoomService;
use App\CustHub\Service\ChRoomSyncService;
use App\CustHub\Service\ChRoomTaskCenterService;
use App\CustHub\Service\ChRoomWelcomeService;
use App\CustHub\Service\ChSendRecordService;
use App\CustHub\Service\ChSmartPushSchemeService;
use App\CustHub\Service\ChSmartPushSchemeTargetTaskService;
use App\CustHub\Service\ChSmartPushSchemeTaskService;
use App\CustHub\Service\ChSmartTagContactStatService;
use App\CustHub\Service\ChSmartTagRuleService;
use App\CustHub\Service\ChTagPresetService;
use App\CustHub\Service\LicenseService;
use App\CustHub\Service\OpenWorkService;
use App\CustHub\Service\RoomInviteService;
use App\CustHub\Service\RoomSyncServiceNew;
use App\CustHub\Service\SmartAnswerService;
use App\CustHub\Work\TxlAgentService;
use App\CustHub\Work\TxlApiService;
use App\Robot\Dto\FileMessageDTO;
use App\Robot\Dto\ImageMessageDTO;
use App\Robot\Dto\QuoteMsgDTO;
use App\Robot\Dto\RobotMsgDto;
use App\Robot\Dto\UrlMessageDTO;
use App\Robot\Dto\VideoMessageDTO;
use App\Robot\Dto\VoiceMessageDTO;
use App\Robot\Service\RobotApiService;
use App\Robot\Service\SendRobotMessageService;
use App\Setting\Service\SettingConfigService;
use App\System\Dto\UserDto;
use Carbon\Carbon;
use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use Hyperf\Di\Annotation\AnnotationCollector;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Mine\MineController;
use Psr\EventDispatcher\EventDispatcherInterface;
use function FriendsOfHyperf\Lock\lock;
use function Hyperf\Coroutine\co;
use function Hyperf\Support\optional;
use function Hyperf\Support\value;

#[Controller(prefix: 'test')]
class Test extends MineController
{
    #[RequestMapping('appInit')]
    public function appInit()
    {
        $userList = ChUser::query()
            ->where('parent_id',0)
            ->get();

        $service = container()->get(AppService::class);
        foreach ($userList as $user){
            $service->bindUser($user->id,$user->account);
        }

    }

    public function setNotify()
    {
        $robot = container()->get(ChRobotMapper::class)->findById(29);
        $apiService = make(Robot::class, [$robot->server_id, $robot->uuid])->gateway();
        $apiService->setNotifyUrl("http://api.sdashi.cn/notify/notice");
    }

    #[RequestMapping('test')]
    public function test()
    {
        $robotId = $this->request->input('robot_id');
        if($robotId){
            $robot = container()->get(ChRobotMapper::class)->findById($robotId);
            $apiService = make(Robot::class, [$robot->server_id, $robot->uuid])->gateway();
            $response = $apiService->getProfile();
            if($response !== false){
                $acctid = $response['acctid'];
                $corpInfo = ChCorp::query()
                    ->where('id',$robot->corp_id)
                    ->first();
                $response = make(OpenWorkService::class,[$corpInfo->auth_corp_id])->getOpenUserid([$acctid]);
                var_dump($response);
            }
        }
        return;

//        $data = [
//            'user_id'     => 1,
//            'form_room_id' => 0,
//            'sender_id'   => "1688857476621312",
//            'receiver_id' => "7881300924917195",
//            'talk_type'   => 1,
//            'record_id'   => 1,
//        ];
//
//        event(new TalkEvent(TalkEventConstant::EVENT_TALK, $data));
//        $condition_conf=json_decode('{"crowd_conf":{"conf":[],"type":""},"custom_conf":{"conf":[{"out":{"gender":"","remarks":[],"remark_type":1,"add_end_time":"2025-11-05 23:59:59","corp_tag_ids":["14073751025934278"],"smart_tag_ids":[],"add_start_time":"2025-11-04 00:00:00","corp_match_type":0,"is_with_remarks":0,"smart_match_type":0},"isset":{"gender":"","remarks":[],"remark_type":1,"add_end_time":"","corp_tag_ids":[],"smart_tag_ids":[],"add_start_time":"","corp_match_type":0,"is_with_remarks":0,"smart_match_type":0},"exclude_switch":1}],"type":2}}',true);
//        //查询用户
//        $customIds = container()->get(ChCrowSendingService::class)->getContactList(10251, 68, $condition_conf['custom_conf']);
//        //查询群
//        //$crowdIds = container()->get(ChCrowSendingService::class)->getCrowdList(19, 6, 1, $condition_conf['crowd_conf']);
//        var_dump($customIds);
//        return;
//        $json = '{"tenant_id":0,"guid":"6b6450df-b4e2-8f6e-2ada-387531c9c619","user_id":"1688856178592992","request_id":"525c4516dfc026f8d60e75585037129f","custom_param":"1_6_320000_320100","cmd":15000,"base64_raw_data":"CgcIABIDCgEy","from_room_id":"10760504277510313","is_room_notice":1,"msg_data":{"at_list":[],"content":"2","reply":null},"msg_server_id":1074617,"msg_type":2,"msg_unique_identifier":"111259509202459744","receiver_id":1688856178592992,"sender_id":7881303132013627,"sender_name":"","timestamp":1758772813,"seq":22222151,"sender":"7881303132013627","receiver":"1688856178592992","msgtype":2,"content":{"content":"2","msg_type":"text"},"at_list":[],"is_robot":false,"is_room":1,"robot_id":19,"chat_record_id":90711}';
//        $robot= container()->get(ChRobotMapper::class)->findById(19);
//        var_dump(json_decode($json,true));
//        container()->get(ChMaterialService::class)->autoCollect($robot,json_decode($json,true));
//        container()->get(ChRoomInviteSchemeService::class)->getActiveRoomList(1,1,2,[
//            'filter_mode' => 0,
//            'config' => [
//                'role' => [0,1,2]
//            ]
//        ]);
        //return;
//        $robotMapper = container()->get(ChRobotMapper::class);
//        $robot = $robotMapper->findById(2);
//        $uuid = \Hyperf\Stringable\Str::uuid()->toString();
//        $robotMapper->update($robot->id,['uuid'=>$uuid]);
//        $robotMapper->clearCache($robot->id);
       // $apiService = make(Robot::class,[$robot->server_id,$robot->uuid])->gateway();
//        $apiService->setNotifyUrl("http://devapi.sdashi.cn/notify/notice");
        //1718e22c-6c54-4100-a0b0-b834b28f0db9 6a109674-6336-4109-8de5-a0a7ed0a73a7
//        $response = $apiService->restoreClient('1688857338488676','1_6_320000_320100');
//        $apiService->stopClient();
//        $apiService->restoreClient('1688857338488676','1_6_320000_320100');
//        $apiService->checkLoginQrCode();
//        $apiService->checkLogin();

//        $response = $apiService->getLoginQrCode();
//        var_dump($response);
//        $apiService->verifyLoginQrcode('766830');
//        $response = $apiService->getRoomDetail(['10878190561302986']);
//        var_dump($response);
//        $apiService->sendTextMsg('哈哈哈[微笑]','7881300924917195');
//        $apiService->getCorpInfo();
//        $apiService->getCorpInfo(['1970325002090154']);

//        $apiService->getSessionPage();

//        $content = [
//            [
//                'subtype' => 1,
//                'text' => '7881303132013627'
//            ],
//            [
//                'subtype' => 0,
//                'text' => ' 哈哈哈哈哈'
//            ],
//            [
//                'subtype' => 2,
//                'text' => '[微笑]'
//            ],
//        ];
//        $apiService->sendMixTxtMsg($content,'10868817197988389');
        $fileUrl = 'https://pic.wikeyun.cn/wikeyun/20241012/6fd7d0955b17586c86fa130c38e180a9.mp4';
        $filename = '双人8终.mp4';
        $msgData = new RobotMsgDto();
        $msgData->setMsgType(MsgTypeConstants::VIDEO)
            ->setContent($fileUrl)
            ->setToId("7881300924917195")
            ->setServerId($robot->server_id)
            ->setFilename($filename)
            ->setUuid($robot->uuid);
        make(\App\Robot\Service\RobotMessageService::class, [$msgData])->sendMessage();

//        $apiService->cdnToUrl($response['fileAesKey'],$response['fileId'],$response['fileMd5']);
//        $apiService->sendGif('https://wework.qpic.cn/wwpic3az/861656_DaujzDb9ThGMJw-_1709869537/0','7881300924917195');
//        $content = (new ImageMessageDTO())
//            ->setFileMd5($response['fileMd5'])
//            ->setToId('7881300924917195')
//            ->setFileId($response['fileId'])
//            ->setFileAesKey($response['fileAesKey'])
//            ->setFilename($fileName)
//            ->setFileSize($response['fileSize']);
//        $apiService->sendImageMsg($content);
         //图片和视频消息存在问题
//        $fileUrl = 'https://img.sdashi.cn/uploadfile/20250807/811912156114882560.txt';
//        $fileName = '新建文本文档.txt';
//        $response = $apiService->upload($fileUrl,$fileName,5);
//        $content = (new FileMessageDTO())
//            ->setFilename($fileName)
//            ->setFileId($response['file_id'])
//            ->setFileSize($response['file_size'])
//            ->setFileAesKey($response['file_aes_key'])
//            ->setToId('7881300924917195');
//        $apiService->sendFileMsg($content);

//        $fileUrl = 'https://pic.wikeyun.cn/wikeyun/20250820/c38f819665fec914fa04c56506d7822d.mp3';
//        $fileName = 'c38f819665fec914fa04c56506d7822d.mp3';
//        $response = $apiService->upload($fileUrl,$fileName,5);
//        $content = (new VoiceMessageDTO())
//            ->setToId('7881300924917195')
//            ->setFileSize($response['file_size'])
//            ->setFileAesKey($response['file_aes_key'])
//            ->setFileId($response['file_id'])
//            ->setVoiceTime(7);
//        $apiService->sendVoiceMsg($content);

//        $content = (new UrlMessageDTO())
//            ->setToId('7881300924917195')
//            ->setDesc("霸王餐福利满满")
//            ->setTitle('霸王餐')
//            ->setLinkUrl('http://www.baidu.com')
//            ->setIconUrl('https://pic.wikeyun.cn/wikeyun/20230705/031df8082ce98af1fc6a7b43ec812778.jpg');
//        $apiService->sendUrlMsg($content);

        $toId = '10825492853179024';
        $filename = '';
//        $content = json_decode('{
//		"desc": "5元吃外卖 天天不重样",
//		"appid": "wx328b3a1c890faae5",
//		"title": "饭团团霸王餐",
//		"icon_url": "https://pic.wikeyun.cn/wikeyun/20250820/537ea173748da901955c1b1780c405da.png",
//		"pagepath": "pages/agency/index.html?url=pages/home/index&user_id=1128033",
//		"username": "gh_8ae1b785c444@app",
//		"cover_url": "https://pic.wikeyun.cn/wikeyun/20250820/e6259aa03418fcef142f52e971d3336f.png"
//	}',true);
//        $msgType = MsgTypeConstants::CUSTOM_MINI_PROGRAM;
//        $filename = '';

//        $content = '[憨笑]';
//        $msgType = MsgTypeConstants::TEXT;

//        $content = 'https://img.sdashi.cn/uploadfile/20250730/809074984604495872.gif';
//        $msgType = MsgTypeConstants::EMOJI;

//        $content = '7881303132013627';
//        $msgType = MsgTypeConstants::PERSONAL_CARD;

//        $content = [
//            'title' => '微客云',
//            'address' => '江苏省南京市雨花台区数字大道518号',
//            'latitude' => 31.97,
//            'longitude' => 118.78
//        ];
//        $msgType = MsgTypeConstants::IMAGE;
//        $content = 'https://pic.wikeyun.cn/wikeyun/20241012/6fd7d0955b17586c86fa130c38e180a9.mp4';
//        $filename = '双人8终.mp4';
//        $content = 'https://img.sdashi.cn/uploadfile/20250827/ufrzj4mxp3e1y3yugc0o.jpg';
//        $apiService->upload($content,'ufrzj4mxp3e1y3yugc0o.jpg',1);
//        $filename = 'deb7f00722c1c6ee52b87d10f22c53d2.png';
//        $msgData = new RobotMsgDto();
//        $msgData->setMsgType($msgType)
//            ->setContent($content)
//            ->setToId($toId)
//            ->setServerId($robot->server_id)
//            ->setFilename($filename)
//            ->setUuid($robot->uuid);
//
//        //消息发送服务
//        make(\App\Robot\Service\RobotMessageService::class, [$msgData])->sendMessage();

//        $file = 'https://pic.wikeyun.cn/wikeyun/20250820/e6259aa03418fcef142f52e971d3336f.png';
//        $apiService->snsUpload($file,1);

//        $apiService->dataSync(1,19751348);
//        $result =  $apiService->roomidToOpenroomid("10700865455559636");
//        $openUser = array_shift($result);
//        $userid = $openUser['open_user_id'];
//        var_dump($userid);
//        $apiService->syncCollectionMsg();
//        $client = make(\Nashgao\MQTT\Client::class);
//        $client->publish('topic/test', 'message', 1);
//        $data = $apiService->dataSync(1);
//        var_dump($data);
//        //10844808479917374
//        $msgData = new RobotMsgDto();
//        $msgData->setMsgType(MsgTypeConstants::CROWD)
//            ->setContent([
//                'member_list' => ['7881301132247662']
//            ])
//            ->setToId("10844808479917374")
//            ->setServerId($robot->server_id)
//            ->setFilename($filename)
//            ->setUuid($robot->uuid);
//        make(\App\Robot\Service\RobotMessageService::class, [$msgData])->sendMessage();
//        $apiService->dataSync(1,12042097);
//        $roomInfo = ChRoom::query()
//            ->where('id',1005)
//            ->first();
//        container()->get(ChRoomAutoTagConfigService::class)->getMeetTheConditionScheme($roomInfo->main_uid,$roomInfo->room_wxid,$roomInfo->room_name,$roomInfo->room_member_count);
    }

    public function testSendMsg()
    {
        container()->get(SendRobotMessageService::class)->handle([
            'robot_id' => 29,
            'msg_type' => 'text',
            'content' => "每天循环发送\n老板\n你好哇～😚",
            'to_id' => "7881300924917195"
        ]);
    }

    public function testQuoteMsg()
    {
        $robot = container()->get(ChRobotMapper::class)->findById(25);
        $robotApiService = make(RobotApiService::class, [$robot->server_id, $robot->robot_key]);

        //引用自己的情况，user_id接收人的ID，sendId使用发送人的
        //引用他人的消息，user_id和sendId都使用发送人的
        $quoteMsgData = (new QuoteMsgDTO())
            ->setSendId("7881300924917195")
            ->setMsg("这是弄啥呢")
            ->setSendTime(time())
            ->setUserId("7881300924917195")
            ->setContent([
                'content' => "，"
            ])->setAppinfo("4685786882828467052");

        $rst = $robotApiService->sendQuoteMsg($quoteMsgData);
    }

    #[GetMapping('testScanDel')]
    public function testScanDel()
    {
       $keys = (new RedisCluster())->scan('humx_redis_cluster:*');
       redis()->del($keys);
    }

    #[GetMapping('testLock')]
    public function testLock()
    {

//        $lua = <<<'LUA'
//-- 获取传入的键名
//local key = KEYS[1]
//
//-- 从 Redis 获取该键的值
//local value = redis.call("GET", key)
//
//-- 返回值
//return value
//LUA;
//
//        $result = redis()->eval($lua, ['lock:humx_foo'],1 );
//        var_dump($result);

        $lock = lock($name = 'humx_foo', $seconds = 3600, $owner = null);
        try {
            $lock->block(5);

            // 等待最多5秒后获取的锁...
        } catch (LockTimeoutException $e) {
            // 无法获取锁...
        } finally {
            optional($lock)->release();
        }
    }

    #[RequestMapping('testMsg')]
    public function testMsg()
    {
        var_dump($this->request->all());
    }
}